﻿using HCQ2_Model;
using HCQ2UI_Helper;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace HCQ2WebAPI_Logic.Filters
{
    /// <summary>
    ///  记录接口请求日志过滤器
    /// </summary>
    public class RequestLogFilterAttribute : ActionFilterAttribute
    {
        /// <summary>
        ///  本次请求主键code
        /// </summary>
        private string logCode = string.Empty;
        /// <summary>
        ///  Action执行之前验证
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(HttpActionContext filterContext)
        {
            try
            {
                //请求接口
                string[] func = filterContext.Request.RequestUri.LocalPath.Trim('/').Split('/');
                var task = filterContext.Request.Content.ReadAsStreamAsync();
                string param = GetRequestParams(filterContext);
                //using (Stream sm = task.Result)
                //{
                //    if (sm != null && sm.Length>0)
                //    {
                //        sm.Seek(0, System.IO.SeekOrigin.Begin);
                //        int len = (int)sm.Length;
                //        byte[] inputByts = new byte[len];
                //        sm.Read(inputByts, 0, len);
                //        sm.Close();
                //        param = Encoding.UTF8.GetString(inputByts);
                //    }
                //}
                //if (!string.IsNullOrEmpty(param))
                //    param = param.Trim().Replace(" ", "");
                T_VRRequestLog log = new T_VRRequestLog
                {
                    logCode = HCQ2_Common.Helper.GetGuid,
                    ip = HttpContext.Current.Request.UserHostAddress,
                    func = func[2] + "/" + func[3],
                    @params = param,
                    requestDate = DateTime.Now
                };
                int mark = OperateContext.Current.bllSession.T_VRRequestLog.Add(log);
                if (mark > 0)
                    logCode = log.logCode;
            }
            catch
            { }
            base.OnActionExecuting(filterContext);
        }
        /// <summary>
        ///   Action执行之后验证
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuted(HttpActionExecutedContext filterContext)
        {
            try
            {
                //接口响应是否成功
                var IsSuccess = filterContext.ActionContext.Response.IsSuccessStatusCode;
                if (IsSuccess && !string.IsNullOrEmpty(logCode))
                {
                    OperateContext.Current.bllSession.T_VRRequestLog.Modify(new T_VRRequestLog { isSolve = true }, s => s.logCode.Equals(logCode), "isSolve");
                }
            }
            catch { }
            logCode = null;
            base.OnActionExecuted(filterContext);
        }

        /// <summary>
        ///  获取请求参数
        /// </summary>
        /// <param name="filterContext"></param>
        /// <returns></returns>
        private string GetRequestParams(HttpActionContext filterContext)
        {
            string param = string.Empty;
            try
            {
                //获取POST请求数据  
                var task = filterContext.Request.Content.ReadAsStreamAsync();
                using(Stream sm = task.Result)
                {
                    if(sm!=null && sm.Length > 0)
                    {
                        sm.Position = 0;
                        using(StreamReader reader = new StreamReader(sm, Encoding.UTF8))
                        {
                            param = reader.ReadToEnd().ToString();
                        }
                    }
                    else
                    {
                        //获取Get请求数据
                        param = filterContext.Request.RequestUri.Query;
                    }
                }
            }
            catch { }
            if (!string.IsNullOrEmpty(param))
                param = param.Trim().Replace(" ", "");
            return param;
        }
    }
}